<?php
// +----------------------------------------------------------------------
// | Tpli [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 附件管理
// +----------------------------------------------------------------------
namespace app\base\controller;

use think\Db;
use app\base\controller\Base;
use app\base\model\Attachment as AttachmentModel;
use think\facade\Env;

class Attachment extends Base
{
  public function lst()
  {
    $model = new AttachmentModel();
    $post = $this->request->param();
    $attachment = $model->getAll($post);
    $this->assign('attachment',$attachment);
    return $this->fetch();
  }

  //审核
  public function audit()
  {
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    if($id > 0) {
      if($this->request->isPost()) {
        $model = new AttachmentModel();
        $post = $this->request->post();
        $result = $model->audit($post,$id);
        if(!$result) {
          return $this->error('审核提交失败');
        } else {
          addLog($id);//写入日志
          return $this->success('审核提交成功','base/attachment/lst');
        }
      }
    } else {
      return $this->error('id不正确');
    }
  }

  public function delete()
  {
    if($this->request->isAjax()) {
      $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
      $attachment = Db::name('attachment')->where('id',$id)->value('filepath');
      if(file_exists(Env::get('root_path').'public'.$attachment)) {
        if(unlink(Env::get('root_path').'public'.$attachment)) {
          if(false == Db::name('attachment')->where('id',$id)->delete()) {
            return $this->error('删除失败');
          } else {
            addLog($id);//写入日志
            return $this->success('删除成功','base/attachment/lst');
          }
        } else {
          return $this->error('删除失败');
        }
      } else {
        if(false == Db::name('attachment')->where('id',$id)->delete()) {
          return $this->error('删除失败');
        } else {
          addLog($id);//写入日志
          return $this->success('删除成功','base/attachment/lst');
        }
      }
    }
  }


  public function download()
  {
    if($this->request->isAjax()) {
      $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
      if($id > 0) {
        //获取下载链接
        $data = Db::name('attachment')->where('id',$id)->find();
        $res['data'] = $data['filepath'];
        $res['name'] = $data['filename'];
        //增加下载量
        Db::name('attachment')->where('id',$id)->setInc('download',1);
        $res['code'] = 1;
        addLog($id);
        return json($res);
      } else {
        return $this->error('错误请求');
      }
    }
  }

}
